<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="机构级别" prop="orglevel">
          <el-select v-model="formInline.orglevel" placeholder="机构级别" clearable>
            <el-option
              v-for="item in optionss"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="机构编号">
          <el-input v-model="formInline.strOrgnum" placeholder="机构编号" clearable />
        </el-form-item>
        <el-form-item label="机构名称">
          <el-input v-model="formInline.strOrgname" placeholder="机构名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button type="primary" icon="el-icon-edit" @click="openAdd('form')">添加</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-dialog :title="dialogTitleType" :visible.sync="dialogFormVisible">
      <el-form ref="form" :model="form" :rules="rules" label-position="left" label-width="100px">
        <el-row :gutter="40">
          <el-col :span="12">
            <el-form-item label="机构名称" prop="strOrgname">
              <el-input v-model="form.strOrgname" placeholder="机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构等级" prop="iOrglevel">
              <el-select v-model="form.iOrglevel" placeholder="机构等级">
                <el-option
                  v-for="item in optionss"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有下级" prop="itype">
              <el-select v-model="form.itype" placeholder="是否有下级" @change="getOrgBylevel">
                <el-option value="0" label="是">是</el-option>
                <el-option value="1" label="否">否</el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="strTel">
              <el-input v-model="form.strTel" placeholder="联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="法人" prop="strLegal">
              <el-input v-model="form.strLegal" placeholder="法人" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="机构所属地区" prop="strSheng">
              <el-cascader
                size="large"
                :options="options"
                v-model="form.strSheng"
                :show-all-levels="false"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="机构所在地址" prop="strAddr">
          <el-input v-model="form.strAddr" placeholder="机构所在地址" />
        </el-form-item>
        <el-form-item label="机构下级">
          <el-select v-model="form.numbers" multiple placeholder="请选择机构下级">
            <el-option
              v-for="item in orgList"
              :key="item.id"
              :label="item.strOrgname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false, $refs['form'].resetFields()">取 消</el-button>
        <el-button type="primary" @click="success('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="机构详情" :visible.sync="dialogFormDatil">
      <el-form ref="form" :model="formDatil" label-width="100">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="机构编号">
              <el-input v-model="formDatil.strOrgnum" placeholder="机构编号" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构名称">
              <el-input v-model="formDatil.strOrgname" placeholder="机构名称" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="机构等级">
              <el-select v-model="formDatil.iOrglevel" placeholder="机构等级" disabled>
                <el-option
                  v-for="item in optionss"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input v-model="formDatil.strTel" placeholder="联系方式" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="法人">
              <el-input v-model="formDatil.strLegal" placeholder="法人" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="机构所属地区" prop="strSheng">
              <el-cascader
                size="large"
                :options="options"
                v-model="formDatil.strSheng"
                :show-all-levels="false"
                disabled
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="机构所在地址">
          <el-input v-model="formDatil.strAddr" placeholder="机构所在地址" disabled />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormDatil = false">关闭</el-button>
      </div>
    </el-dialog>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="序号" width="60" />
      <el-table-column prop="strOrgnum" label="机构编号" width="150" />
      <el-table-column prop="strOrgname" label="机构名称" width="150" />
      <el-table-column prop="strOrglevel" label="机构等级" />
      <el-table-column prop="strParorgnum" label="机构上级" />
      <el-table-column label="操作" min-width="220">
        <template slot-scope="{row}">
          <template v-if="iOrgsysnum === -1||row.iOrgsysnum === iOrgsysnum">
            <el-button type="info" size="mini" @click="getOrgDatil(row)">查看</el-button>
            <el-button type="primary" size="mini" @click="updateOrg(row)">修改</el-button>
            <el-button type="danger" size="mini" @click="deleteOrg(row)">删除</el-button>
          </template>
          <template v-else>
            <el-button type="info" size="mini" @click="getOrgDatil(row)">查看</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="getOrgList"
    />
  </div>
</template>
<script>
import {
  getOrgList,
  deleteOrg,
  getOrgListByelvel,
  addOrgInfo,
  queryNextOrg,
  updOrgInfo,
  queryNextbyOrgsysnum
} from '@/api/system/system'
import Pagination from '@/components/Pagination'
import {
  validatePhone,
  validateOrgName,
  validatestrLegal,
  validatestrAddr
} from '../../utils/validateForm'
import { regionData, CodeToText, TextToCode } from 'element-china-area-data'
import { mapGetters } from 'vuex'

export default {
  components: {
    Pagination
  },
  data() {
    return {
      formInline: {
        orglevel: '',
        strOrgnum: '',
        strOrgname: ''
      },
      form: {
        strOrgnum: '',
        strOrgname: '',
        iOrglevel: '',
        itype: '',
        strTel: '',
        strLegal: '',
        strSheng: [],
        strAddr: '',
        numbers: []
      },
      formDatil: {
        strOrgnum: '',
        strOrgname: '',
        iOrglevel: '',
        itype: '',
        strTel: '',
        strSheng: [],
        strLegal: '',
        strAddr: ''
      },
      tableData: [],
      rules: {
        strOrgname: [
          { required: true, validator: validateOrgName, trigger: 'blur' }
        ],
        iOrglevel: [
          { required: true, message: '请选择机构等级', trigger: 'change' }
        ],
        itype: [
          { required: true, message: '请选择是否有下级', trigger: 'change' }
        ],
        strTel: [
          {
            required: true,
            validator: validatePhone,
            trigger: 'blur'
          }
        ],
        strLegal: [
          { required: true, validator: validatestrLegal, trigger: 'blur' }
        ],
        strSheng: [
          {
            required: true,
            message: '请选择所属地区',
            trigger: 'change'
          }
        ],
        strAddr: [
          { required: true, validator: validatestrAddr, trigger: 'blur' }
        ]
      },
      dialogFormVisible: false,
      dialogFormDatil: false,
      dialogTitleType: '',
      total: 0,
      limit: 5,
      pagenum: 1,
      currentpage: 1,
      layout: 'total, prev, pager, next, jumper',
      orgList: [],
      options: regionData,
      optionss: [
        {
          value: '1',
          label: '总行'
        },
        {
          value: '2',
          label: '分行'
        },
        {
          value: '3',
          label: '支行'
        },
        {
          value: '4',
          label: '网点'
        }
      ]
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum'])
  },
  created() {
    this.getOrgList()
  },
  methods: {
    onSubmit() {
      getOrgList({
        pagenum: 1,
        iOrglevel: this.formInline.orglevel,
        strOrgnum: this.formInline.strOrgnum,
        strOrgname: this.formInline.strOrgname,
        iOrgsysnum: this.$store.getters.iOrgsysnum
      }).then(res => {
        this.tableData = res && res.data
        this.total = res.total
      })
    },
    handleChange(value) {
      console.log(value)
    },
    getOrgList() {
      getOrgList({
        pagenum: this.pagenum,
        iOrgsysnum: this.$store.getters.iOrgsysnum
      }).then(res => {
        this.tableData = res && res.data
        this.total = !res ? 0 : res.total
      })
    },
    deleteOrg(row) {
      var orgName = row.strOrgname
      this.$confirm(
        '此操作将永久删除机构：' + orgName + ', 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          deleteOrg({ id: row.id, iOrgsysnum: row.iOrgsysnum }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getOrgList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    getOrgDatil(row) {
      const sheng = TextToCode[row.strSheng].code
      const shi = TextToCode[row.strSheng][row.strShi].code
      const qu = TextToCode[row.strSheng][row.strShi][row.strQu].code
      const addresss = sheng + ',' + shi + ',' + qu
      this.formDatil.iOrglevel = row.iOrglevel + ''
      this.formDatil.strOrgnum = row.strOrgnum
      this.formDatil.strOrgname = row.strOrgname
      this.formDatil.strTel = row.strTel
      this.formDatil.strSheng = addresss.split(',')
      this.formDatil.strLegal = row.strLegal
      this.formDatil.strAddr = row.strAddr
      this.dialogFormDatil = true
    },
    openAdd() {
      this.dialogFormVisible = true
      this.form = {
        strOrgnum: '',
        strOrgname: '',
        iOrglevel: '',
        itype: '',
        strTel: '',
        strLegal: '',
        strSheng: [],
        strAddr: '',
        numbers: []
      }
      this.orgList = []
      this.$nextTick(() => {
        this.$refs['form'].resetFields()
      })
      this.dialogTitleType = '新增机构'
    },
    updateOrg(row) {
      const sheng = TextToCode[row.strSheng].code
      const shi = TextToCode[row.strSheng][row.strShi].code
      const qu = TextToCode[row.strSheng][row.strShi][row.strQu].code
      const addresss = sheng + ',' + shi + ',' + qu
      this.dialogTitleType = '修改机构'
      this.form.id = row.id
      this.form.iOrglevel = row.iOrglevel.toString()
      this.form.strOrgnum = row.strOrgnum
      this.form.strOrgname = row.strOrgname
      this.form.strTel = row.strTel
      this.form.strSheng = addresss.split(',')
      this.form.strLegal = row.strLegal
      this.form.strAddr = row.strAddr
      this.form.iOrgsysnum = row.iOrgsysnum
      queryNextOrg({
        iOrglevel: row.iOrglevel,
        iOrgsysnum: row.iOrgsysnum
      }).then(res => {
        this.orgList = res && res.data
      })
      queryNextbyOrgsysnum({
        iOrgsysnum: row.iOrgsysnum,
        iOrglevel: row.iOrglevel
      }).then(res => {
        const num = []
        res &&
          res.data.map(item => {
            num.push(item.id)
          })
        if (JSON.stringify(num) === '[]') {
          this.form.itype = '1'
        } else {
          this.form.itype = '0'
        }
        this.form.numbers = num
      })
      this.dialogFormVisible = true
    },
    success(formName) {
      if (this.dialogTitleType === '新增机构') {
        if (this.form.itype === '1') {
          this.form.numbers = ''
        } else {
          if (this.form.numbers.length > 0) {
            this.form.numbers = this.form.numbers
          } else {
            this.form.numbers = ''
          }
        }
        const diqu = this.form.strSheng
        this.form.strSheng = CodeToText[diqu[0]]
        this.form.strShi = CodeToText[diqu[1]]
        this.form.strQu = CodeToText[diqu[2]]
        delete this.form.id && this.form.id
        this.$refs[formName].validate(valid => {
          if (valid) {
            addOrgInfo(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '新增成功!'
              })
              this.$refs[formName].resetFields()
              this.dialogFormVisible = false
              this.getOrgList()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else if (this.dialogTitleType === '修改机构') {
        if (this.form.itype === '1') {
          this.form.numbers = ''
        } else {
          if (this.form.numbers.length > 0) {
            this.form.numbers = this.form.numbers
          } else {
            this.form.numbers = ''
          }
        }
        const diqu = this.form.strSheng
        this.form.strSheng = CodeToText[diqu[0]]
        this.form.strShi = CodeToText[diqu[1]]
        this.form.strQu = CodeToText[diqu[2]]
        this.$refs[formName].validate(valid => {
          if (valid) {
            updOrgInfo(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.$refs[formName].resetFields()
              this.dialogFormVisible = false
              this.getOrgList()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    getOrgBylevel(val) {
      if (val === '0') {
        var level = this.form.iOrglevel
        if (level === '') {
          this.$message({
            type: 'info',
            message: '请先选择机构等级'
          })
          this.form.itype = '1'
        } else {
          var orglevel = parseInt(level)
          getOrgListByelvel({ iOrglevel: orglevel + 1 }).then(res => {
            this.orgList = res.data
          })
        }
      }
    }
  }
}
</script>
